package com.shuiyun.chat.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.shuiyun.chat.entity.bo.ChatGroupBO;
import com.shuiyun.chat.entity.bo.ChatGroupUpdateBO;
import com.shuiyun.chat.entity.po.ChatGroupPO;
import com.shuiyun.chat.entity.vo.ChatGroupVO;
import com.shuiyun.chat.mapper.ChatGroupMapper;
import com.shuiyun.chat.utils.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shuiyun
 * @since 2021-05-14
 */
@Slf4j
@Service
public class ChatGroupService extends ServiceImpl<ChatGroupMapper, ChatGroupPO>  {

    @Autowired
    ChatGroupMapper chatGroupMapper;

    /**
     * <p>
    * 通过ID获取对象
    * </p>
     *
     */
    public ChatGroupVO get(Long id) {
        ChatGroupPO po = chatGroupMapper.selectById(id);
        return po2vo(po);
    }

    /**
     * <p>
    * 新增对象
    * </p>
     *
     */
    public Long add(ChatGroupBO chatGroupBO) {
        ChatGroupPO chatGroup = new ChatGroupPO();
        BeanUtil.copyProperties(chatGroupBO, chatGroup);
        chatGroupMapper.insert(chatGroup);
        return chatGroup.getId();
    }

    /**
     * <p>
    * 修改对象
    * </p>
     *
     */
    public void update(ChatGroupUpdateBO chatGroupUpdateBO) {
        chatGroupMapper.updateById(BeanUtil.copyProperties(chatGroupUpdateBO, ChatGroupPO.class));
    }

    /**
     * <p>
    * 删除对象
    * </p>
     *
     */
    public void delete(Long id) {
        chatGroupMapper.deleteById(id);
    }

    private ChatGroupVO po2vo(ChatGroupPO po){
        ChatGroupVO chatGroupVO = BeanUtil.copyProperties(po, ChatGroupVO.class);
        List<String> list = JSON.parseArray(po.getUsers(), String.class);
        chatGroupVO.setUsers(new HashSet<>(list));
        return chatGroupVO;
    }

}
